// 引入mongoose
const { default: mongoose } = require("mongoose");

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

// 导入app
const {app}=require('../../app')

// 创建对象规则
const NewsSchema=new mongoose.Schema({
    news_id:String,
    user_id:String,
    user_name:String,
    comments_num:Number,
    cover:Object,
    images:Array,
    type:Number,
    upload_time:Date,
    title:String,
    content:String,
    avatar:String,
    icon:String,
    types:String
})

// 创建对象模型
const NewsList=mongoose.model('newslists',NewsSchema)
// 查询
app.get('/sy/newslist',(req,res)=>{
    // console.log(req.query)
    NewsList.find().then(r=>{
        res.send(r)

    })
})
// 查询详情
app.get('/sy/newslist/detail/:id',(req,res)=>{
    console.log(req.params)
    const {id}=req.params
    NewsList.findOne({id}).then(r=>{
        res.send({
            data:r,
            status:200,
            message:'查找成功'
        })
    })
})
// 新增
app.post('/sy/newslist',(req,res)=>{
    console.log(req.body)
//    const {cover}=req.body
    NewsList.create(req.body).then(r=>{
        // const len=r.cover.images.length
        const rs={
            title:r.title,upload_time:r.upload_time,delivery:r.delivery,
            content:r.content,cover:{images:[r.icon],type:1
        }}
        res.send({
            data:rs,
            status:200,
            message:'创建成功'
        })
        // res.send(r)
    })
})

// 查询
app.get('/sy/getnewslist',(req,res)=>{
    console.log(req.query)
    NewsList.find().then(r=>{
        res.send(r)
    })
})
// 查询 id
app.get('/sy/getnewslists',(req,res)=>{
    console.log(req.query)
    const {_id}=req.body
    NewsList.findOne({'_id':_id}).then(r=>{
        console.log(r)
        res.send({
            data:r,
            status:'查找到了'
        })
    })
})

// 删除
app.delete('/sy/newslist/:id',(req,res)=>{
    console.log(req.body)
    const {id}=req.body
    NewsList.deleteOne({_id:id}).then(r=>{
                res.send(true)
    })
})

// 删除
// app.post('/sy/delnewslist/:id',(req,res)=>{
//     console.log(req.body)
//     const {id}=req.body
//     NewsList.deleteOne({_id:id}).then(r=>{
//         res.send(true)
//     })
// })

// 编辑
// app.put('/sy/delnewslist/:id',async(req,res)=>{
//     console.log(req.body)
//     const {id}=req.body
//     NewsList.findByIdAndUpdate({_id:id}).then(r=>{
//         res.send(true)
//     })
// })

// app.post('/sy/newslist/upload',upload.single('avatar'),(req,res,next)=>{
//     console.log(req.file)
//     const avatar=`/upload/${req.file.filename}`
//     const {title,upload_time,delivery,types,content}=this.obj
//     res.send({avatar})
//     NewsList.create({avatar,title,upload_time,delivery,types,content}).then(r=>{
//         // res.send({
//         //     data:r,
//         //     status:200,
//         //     message:'创建成功'
//         // })
//         res.send(r)
//     })
// })

// 导出
module.exports={
    NewsList
}